package com.liqi.web.controller.device;

import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.liqi.common.core.domain.R;
import com.liqi.common.utils.Base64ToMultipartFile;
import com.liqi.common.utils.StringUtils;
import com.liqi.common.utils.mqtt.MqttConfig;
import com.liqi.common.utils.mqtt.MqttPushClient;
import com.liqi.common.utils.uuid.GenerateCodeUtils;
import com.liqi.device.domain.DvRemoteScreenshot;
import com.liqi.device.service.IDvRemoteScreenshotService;
import com.liqi.monitor.dto.GetScreenshotReq;
import com.liqi.monitor.dto.GetScreenshotRsp;
import com.liqi.monitor.dto.SaveScreenshotReq;
import com.liqi.sms.utils.SmartHttp;
import com.liqi.web.controller.common.minio.MinIoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.liqi.common.annotation.Log;
import com.liqi.common.core.controller.BaseController;
import com.liqi.common.core.domain.AjaxResult;
import com.liqi.common.enums.BusinessType;
import com.liqi.common.utils.poi.ExcelUtil;
import com.liqi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 远程截屏图片保存Controller
 *
 * @author ruoyi
 * @date 2022-11-01
 */
@RestController
@Api(tags = "远程操作命令")
@RequestMapping("/device/screenshot")
public class DvRemoteScreenshotController extends BaseController
{
    @Autowired
    private IDvRemoteScreenshotService dvRemoteScreenshotService;

    @Autowired(required = false)
    private MinIoService minIoService;

    @Value("${remote.port}")
    private String port;
    @Autowired
    private MqttConfig mqttConfig;

    /**
     * 查询远程截屏图片保存列表
     */
    @PreAuthorize("@ss.hasPermi('system:screenshot:list')")
    @GetMapping("/list")
    public TableDataInfo list(DvRemoteScreenshot dvRemoteScreenshot)
    {
        startPage();
        List<DvRemoteScreenshot> list = dvRemoteScreenshotService.selectDvRemoteScreenshotList(dvRemoteScreenshot);
        return getDataTable(list);
    }

    /**
     * 导出远程截屏图片保存列表
     */
    @PreAuthorize("@ss.hasPermi('system:screenshot:export')")
    @Log(title = "远程截屏图片保存", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, DvRemoteScreenshot dvRemoteScreenshot)
    {
        List<DvRemoteScreenshot> list = dvRemoteScreenshotService.selectDvRemoteScreenshotList(dvRemoteScreenshot);
        ExcelUtil<DvRemoteScreenshot> util = new ExcelUtil<DvRemoteScreenshot>(DvRemoteScreenshot.class);
        util.exportExcel(response, list, "远程截屏图片保存数据");
    }

    /**
     * 获取远程截屏图片保存详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:screenshot:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(dvRemoteScreenshotService.selectDvRemoteScreenshotById(id));
    }


    /**
     * 删除远程截屏图片保存
     */
    @PreAuthorize("@ss.hasPermi('system:screenshot:remove')")
    @Log(title = "远程截屏图片保存", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(dvRemoteScreenshotService.deleteDvRemoteScreenshotByIds(ids));
    }


    /**
     * 远程截屏
     *screenshot(0=双屏，1=主屏，2=附屏)
     */
    @ApiOperation("发布远程拉取截屏信息")
    @PostMapping("/publishGetScreenshot")
    public R<String> publishGetScreenshot(@RequestBody @Valid  GetScreenshotReq getScreenshotReq) {
        String messageCode = GenerateCodeUtils.getSequnce();
        getScreenshotReq.setMessageCode(messageCode);
        getScreenshotReq.setCommandType(4);
        String deviceId = getScreenshotReq.getDeviceId();
        MqttPushClient client = mqttConfig.getDeviceIdMqttPushClient(deviceId);
        String jsonRequest = JSON.toJSONString(getScreenshotReq);
        client.publish(0, false, deviceId, jsonRequest);
        return R.ok(messageCode);

    }
//    /**
//     * 远程截屏
//     *screenshot(0=双屏，1=主屏，2=附屏)
//     */
//    @ApiOperation("保存中间件最新的远程截屏")
//    @PostMapping("/saveScreenshot")
//    public R<GetScreenshotRsp> saveScreenshot(@RequestBody @Valid SaveScreenshotReq saveScreenshotReq) {
//
//        DvRemoteScreenshot remoteScreenshot=new DvRemoteScreenshot();
//
//        try {
//		String base64 =saveScreenshotReq.getScreenshot();
//        StringBuilder base = new StringBuilder(base64);
//        if(saveScreenshotReq.getScreenFlag()==1) {
//            base.insert(0,"data:image/jpeg;base64,");
//        }else {
//            base.insert(0,"data:image/jpeg;base64,");
//        }
//        final String[] base64Array = base.toString().split(",");
//        String dataUir = base64Array[0];
//        String data = base64Array[1];
//
//
//        MultipartFile multipartFile = new Base64ToMultipartFile(data, dataUir);
//
//        String upload = minIoService.upload(multipartFile);
//
//        remoteScreenshot.setDeviceId(saveScreenshotReq.getDeviceId());
//        remoteScreenshot.setFileUrl(upload);
//        remoteScreenshot.setScreenFlag(saveScreenshotReq.getScreenFlag().toString());
//        remoteScreenshot.setCreateBy(getUsername());
//        remoteScreenshot.setStatus(0);
//        remoteScreenshot.setMessageCode(saveScreenshotReq.getMessageCode());
//
//
//        dvRemoteScreenshotService.insertDvRemoteScreenshot(remoteScreenshot);
//
//
//        } catch (Exception e) {
//            return R.fail("未传入正确的ip");
//        }
//
//        return R.ok(remoteScreenshot);
//    }
    @ApiOperation(value = "获取数据库中最新的远程截屏")
    @GetMapping("/getScreenShot")
    public R getScreenShot(@RequestParam(required = false) String messageCode,@RequestParam String ScreenFlag,@RequestParam(required = false) String deviceId)
    {

        if(StringUtils.isBlank(messageCode)&&StringUtils.isBlank(deviceId)){
            return R.fail("message和deviceId其中都为空");
        }
    DvRemoteScreenshot dvRemoteScreenshot=new DvRemoteScreenshot();
    dvRemoteScreenshot.setMessageCode(messageCode);
    dvRemoteScreenshot.setScreenFlag(ScreenFlag);
    dvRemoteScreenshot.setDeviceId(deviceId);
        DvRemoteScreenshot dvRemoteScreenshotRsp = dvRemoteScreenshotService.selectDvRemoteScreenshot(dvRemoteScreenshot);
        if(dvRemoteScreenshotRsp==null){
            return R.ok(null);
        }
        return R.ok(dvRemoteScreenshotRsp.getFileUrl());
    }
}
